<template>
  <div class="project-page">
    <!-- 顶部标题 -->
    <Header :login="true"/>

    <div class="back-page">
      <!-- 页面内容 -->
      <div class="content">
        <!-- 标题 -->
        <div class="breadcrumb">
          <el-link type="primary" @click="onCancel" icon="DArrowLeft"
            >返回</el-link
          >
          <span>首页 / 我的控制台 / 个人账号设置</span>
        </div>
        <div class="infoDiv">
          <el-form
            ref="passwordForm"
            :model="form"
            :rules="rules"
            label-width="150px"
          >
            <el-form-item
              label="当前账户："
              prop="username"
              style="width: 600px"
            >
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item
              label="修改密码："
              prop="password"
              style="width: 600px"
            >
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入8位数密码"
                @blur="validatePassword"
    show-password
              ></el-input>
              <div class="password-strength">
                密码至少包含大小写字母、数字、特殊字符的其中2种
              </div>
            </el-form-item>
            <el-form-item
              label="再次输入密码："
              prop="confirmPassword"
              style="width: 600px"
            >
              <el-input
                v-model="form.confirmPassword"
                type="password"
                placeholder="请再次输入8位数密码"
                @blur="validateConfirmPassword"
    show-password
              ></el-input>
              <div class="password-strength">
                密码至少包含大小写字母、数字、特殊字符的其中2种
              </div>
            </el-form-item>
            <el-form-item label="验证码：" prop="code" style="width: 600px">
  <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
<div class="password-strength">
  <img :src="codeUrl" @click="getCode" class="register-code-img" />
</div>
</el-form-item>
            <div style="text-align: center">
              <el-button
                type="primary"
                @click="onSubmit"
                style="width: 360px; height: 40px"
                >提交</el-button
              >
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { updatePassword } from "@/api/judgeUser.js";
import { getCodeImg } from "@/api/login";
import Header from "@/components/Header.vue";

const router = useRouter();
const userInfo = computed(() => JSON.parse(localStorage.getItem("judgeInfo")));
// 添加这些行以管理验证码相关的状态
const captchaEnabled = ref(false);
const codeUrl = ref("");
const passwordForm = ref(null);
const form = ref({
  username: userInfo.value.name,
  password: "",
  confirmPassword: "",
  code: "", // 添加验证码字段
  uuid: "", // 用于存储验证码的唯一标识符
});

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    const regex =
      /^(?:(?=.*[a-z])(?=.*[A-Z])|(?=.*[a-z])(?=.*\d)|(?=.*[a-z])(?=.*[\W_])|(?=.*[A-Z])(?=.*\d)|(?=.*[A-Z])(?=.*[\W_])|(?=.*\d)(?=.*[\W_])).{8,}$/;
    if (!regex.test(value)) {
      callback(
        new Error(
          "密码至少包含大小写字母、数字、特殊字符的其中2种,并且长度大于8"
        )
      );
    }
    if (form.value.confirmPassword !== "") {
      passwordForm.value.validateField("confirmPassword", () => null);
    }
    callback();
  }
};

const validateConfirmPass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== form.value.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};

const rules = reactive({
  password: [{ validator: validatePass, trigger: "blur" }],
  confirmPassword: [{ validator: validateConfirmPass, trigger: "blur" }],
});
// 获取验证码的方法
const getCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      form.value.uuid = res.uuid; // 存储uuid以便提交时使用
    }
  })
};
const onCancel = () => {
  if (window.history.length > 1) {
    window.history.back(); // 返回上一页
  } else {
    router.push(`judgeProject?type=${route.query.type}`);
    window.location.reload(); // 刷新当前页面
  }
};
const goHome=()=>{
  router.push({
    path: "/index",
  });
}
// 在组件挂载后调用获取验证码的方法
onMounted(() => {
  getCode(); // 页面加载时获取验证码
});
const signOut = () => {
  window.location.replace("/");
  localStorage.clear();
};

// 提交表单时包含验证码信息
const onSubmit = () => {
  passwordForm.value.validate((valid) => {
    if (valid) {
      const data = {
          code: form.value.code, // 添加验证码
          uuid: form.value.uuid, // 添加验证码的UUID
          params: {
          id: userInfo.value.id,
          name: form.value.username,
          password: form.value.password,
        },
      };
      
      updatePassword(data)
        .then((res) => {
          if (res.code == "200") {
            ElMessage.success("密码修改成功,请重新登录");
            signOut()
          } else {
            ElMessage.error("密码修改失败，请重试");
            getCode(); // 如果验证码错误，重新获取验证码
          }
        })
        .catch((error) => {
          console.error("Error during updating password:", error);
          ElMessage.error("发生错误，请检查控制台日志");
        });
    } else {
      ElMessage.warning("请检查输入的信息！");
      return false;
    }
  });
};

const navTo = (path) => {
  router.push(path);
};
</script>

<style scoped>
.project-page {
  font-family: Arial, sans-serif;
}

.back-page {
  min-height: calc(100vh - 56px);
  background: url("../../assets/f87147698f07020d4fea348f49da0166.png") no-repeat
    center center;
  background-size: cover;
}
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ddd;
  background-color: #f5f5f5;
}

.header .logo {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.header .logo span {
  margin-left: 16px;
  font-size: 18px;
  font-weight: bold;
}

.content {
  padding: 20px;
  width: 80%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.breadcrumb {
  color: #888;
  font-size: 14px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  width: 100%;
}

.breadcrumb span {
  margin-left: 20px;
}

h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
  margin-top: 20px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-table td {
  padding: 10px 15px;
  border: 1px solid #ddd;
}

.info-table .table-header {
  background-color: #f0f4f7;
  font-weight: bold;
  color: #333;
}

.info-table .label {
  background-color: #f9f9f9;
  padding: 12px;
  text-align: center;
}

.info-table .data {
  padding: 10px;
  text-align: center;
  width: 30%;
}

.info-table tr:hover {
  background-color: #f5f5f5;
  transition: background-color 0.3s;
}
td {
  text-align: center;
  padding: 10px;
}

:deep(.el-form) {
  display: flex;
  align-items: center;
  flex-direction: column;
}
:deep(.el-form input) {
  height: 30px;
}
:deep(.el-form .el-form-item__content) {
  margin-bottom: 30px;
}
:deep(.el-form button) {
  height: 30px;
}
:deep(.el-form *) {
  font-size: 14px;
  line-height: 30px;
}
:deep(.el-form-item__content) {
  display: flex;
  position: relative;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10%;
  height: 55px;
  border-bottom: 1px solid #eee;
  background-color: #fff;

  .logo {
    display: flex;
    align-items: center;

    img {
      height: 50px;
      margin-right: 8px;
    }

    span {
      font-size: 20px;
      font-weight: bold;
    }
  }

  .user-info {
    display: flex;
    align-items: center;

    span {
      margin-right: 16px;
    }
  }
}
.infoDiv {
  width: 95%;
  height: 80vh;
  background: linear-gradient(
    -45deg,
    #ddf1ff 0%,
    #f0f9ff 10%,
    #ffffff 20%,
    #ffffff 80%,
    #f0f9ff 90%,
    #ddf1ff 100%
  ) !important;
  box-shadow: 0px 0px 15px #969696;
  display: flex;
  justify-content: center;
  align-items: center;
}
.password-strength {
  position: absolute;
  left: 105%;
  width: 100%;
}
</style>
